import createDraw from '@/utils/Draw'
import { Query } from '@/utils/Query'
import { message } from 'ant-design-vue'
import { ref, reactive } from 'vue'
import { useStore } from 'vuex'
import $api from '@/request/api'
export const UseAnnounce = () => {
  const data = []
  const draw = ref()
  const visible = ref(false)
  const loading = ref(false)
  const store = useStore()
  let resultLayer = ''
  let Id = JSON.parse(localStorage.getItem('id'))
  //公告信息
  const noticevalue = ref('')

  //获取区域数据
  const handleClick = (map) => {
    //创建画布
    const source = new ol.source.Vector({
      wrapx: false,
    })
    const layer = new ol.layer.Vector({
      source: source,
    })
    map.value.addLayer(layer)
    //创建画笔,并绘制
    draw.value = createDraw({
      type: 'LineString',
      source: source,
      callback: lineSuccess,
    })
    map.value.addInteraction(draw.value)
    //回调,绘制完成之后,清除画笔
    function lineSuccess(e) {
      //清除画笔
      map.value.removeInteraction(draw.value)
      //获取点数据
      const coordinates = e.feature.getGeometry().getCoordinates()
      //进行缓冲区分析
      var pointObj = new Array()
      //二维数组需要遍历,再添加到对象obj中
      coordinates.forEach((item) => {
        pointObj.push(new Zondy.Object.Point2D(item[0], item[1]))
      })
      //构成折线的弧段
      var gArc = new Zondy.Object.Arc(pointObj)
      //构成线的折线
      var gAnyLine = new Zondy.Object.AnyLine([gArc])
      //设置线要素的几何信息
      var gline = new Zondy.Object.GLine(gAnyLine)
      //设置要素的几何信息
      var fGeom = new Zondy.Object.FeatureGeometry({ LinGeom: [gline] })
      //设置属性结构
      var regAttStr = new Zondy.Object.CAttStruct({
        FldName: ['ID', '面积', '周长', 'LayerID'],
        FldNumber: 4,
        FldType: ['FldLong', 'FldDouble', 'FldDouble', 'FldLong'],
      })
      //实例化CAttDataRow类
      var values = [0, 62.566714, 50.803211, 0]
      var valuesRow = new Zondy.Object.CAttDataRow(values, 1)
      //实例化FeatureBuffBySingleRing类，设置要素缓冲分析必要参数，输出分析结果到缓冲分析结果图层
      var featureBufBySR = new Zondy.Service.FeatureBuffBySingleRing({
        ip: 'localhost',
        port: '6163',
        //设置要素缓冲分析左半径
        leftRad: 0.002,
        //设置要素缓冲分析右半径
        rightRad: 0.002,
      })
      /*设置缓冲分析参数*/
      //设置几何信息
      featureBufBySR.sfGeometryXML = JSON.stringify([fGeom])
      //设置属性结构
      featureBufBySR.attStrctXML = JSON.stringify(regAttStr)
      //设置属性值
      featureBufBySR.attRowsXML = JSON.stringify([valuesRow])
      //设置追踪半径
      featureBufBySR.traceRadius = 0.0001
      //设置缓冲结果的名称以及存放地址
      featureBufBySR.resultName =
        'gdbp://MapGisLocal/wuhan/ds/buffer/sfcls/bufferresult' + Date.now()
      //调用Zondy.Service.AnalysisBase基类的execute方法执行要素缓冲分析，AnalysisSuccess为回调函数。
      featureBufBySR.execute(bufferSuccess, 'post', false, 'json', bufferError)
    }
    //缓冲区分析失败回调函数
    function bufferError() {
      console.log('缓冲区分析失败')
    }
    /**
     * 缓冲区分析成功回调函数，执行裁剪分析
     * @param {object} result 缓冲区分析结果对象
     */
    function bufferSuccess(result) {
      var clspath = result.results[0].Value
      //实例化ClipByLayer类
      var clipParam = new Zondy.Service.ClipByLayer({
        ip: 'localhost',
        port: '6163',
        //源简单要素类的URL
        srcInfo1: 'gdbp://MapGisLocal/wuhan/sfcls/居民区',
        //裁剪框简单要素类的URL
        srcInfo2: clspath,
        //设置结果URL
        desInfo:
          'gdbp://MapGisLocal/wuhan/ds/clip/sfcls/clipresult' + Date.now(),
        infoOptType: 0,
      })
      //调用基类的execute方法，执行图层裁剪分析。AnalysisSuccess为结果回调函数
      clipParam.execute(clipSuccess, 'post', false, 'json', clipError)
    }
    //缓冲区分析成功,添加到图层
    function clipSuccess(result) {
      const resultName = result.results[0].Value
      if (result.succeed) {
        message.success('缓冲区分析成功!')
        resultLayer = new Zondy.Map.GdbpLayer('', [resultName], {
          ip: 'localhost',
          port: 6163,
        })
        map.value.addLayer(resultLayer)
      }
      //查询所裁剪图层的属性
      Query.queryByLayerUrl({
        url: resultName,
        callback: querySuccess,
      })
    }
    //缓冲区裁剪失败回调
    function clipError() {
      console.log('缓冲区裁剪失败')
    }
    //查询成功回调
    function querySuccess(result) {
      //数组遍历获取对应的名称和电话
      result.SFEleArray.forEach((item) => {
        data.push({ name: item.AttValue[4], tel: item.AttValue[5] })
      })
      //2s后显示弹框
      loading.value = true
      setTimeout(() => {
        loading.value = false
        visible.value = true
      }, 2000)
    }
  }
  //点击发布公告
  const handlePulish = (map) => {
    if (noticevalue.value != '') {
      $api
        .publishNotice({ userId: Id, content: noticevalue.value })
        .then((res) => {
          const { code, msg } = res
          if (code == 202) {
            setTimeout(() => {
              visible.value = false
              message.success(`${msg}`)
              map.value.getLayers().array_.splice(5, 2)
              map.value.render()
              noticevalue.value = ''
            }, 1000)
          }
        })
    } else {
      message.error('请输入公告信息!')
    }
  }

  return {
    data,
    visible,
    loading,
    noticevalue,
    handleClick,
    handlePulish,
  }
}
